<?php
// +----------------------------------------------------------------------
// | ThinkBLOG (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author nicholas <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: PrivilegeAction.class.php 145 2012-04-27 09:26:00Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


class PrivilegeAction extends BaseAction {
	
	public $dao;
	
	/**
	 * 初始化
	 * 
	 * @see BaseAction::_initialize()
	 * @access public
	 * @return void
	 */
	public function _initialize() {
		
		parent::_initialize ();
		
		$this->dao = D ( 'Users' );
		
		if (! C ( 'register' )) {
			define ( __NO_REGISTER__, true );
		}
		
		$actions = array ('login', 'authenticate', 'register', 'registration', 'lostPassword', 'sendPassword', 'resetPassword' );
		
		if ($this->hasLogin ()) {
			if (in_array ( ACTION_NAME, $actions )) {
				redirect ( U ( 'Admin/Index/index' ) );
			}
		}
	}
	
	public function _empty() {
		if ($this->hasLogin ()) {
			redirect ( U ( 'Admin/Index/index' ) );
		} else {
			$this->login ();
		}
	}
	
	public function _login() {
		$this->assign ( 'referer', empty ( $_GET ['referer'] ) ? (U ( 'Admin/Index/index' )) : base64_url_decode ( $_GET ['referer'] ) );
		$this->display ( 'login' );
	}
	
	public function login() {
		cookie ( 'auth', NULL );
		$this->_login ();
	}
	
	public function logout() {
		/*if (! $this->submitcheck ()) {
			$this->error ( '', '非法提交', 0 );
		}*/
		cookie ( 'auth', NULL );
		$this->assign ( 'logout', '您已登出。' );
		$this->_login ();
	}
	
	/**
	 * 登陆业务处理
	 *
	 * @access public
	 * @return void
	 */
	public function authenticate() {
		
		if (! $this->submitcheck ()) {
			$this->ajaxReturn ( '', '非法提交', 0 );
		}
		
		$data = $this->r->from ( 'username', 'password', 'rememberme' );
		
		$this->v->addRule ( 'username', 'required', '错误：必须填写用户名' );
		$this->v->addRule ( 'username', 'xssCheck', '错误：请不要在用户名中使用特殊字符' );
		$this->v->addRule ( 'password', 'required', '错误：必须填写密码' );
		
		if ($row = $this->v->run ( $data )) {
			$this->ajaxReturn ( '', $this->getErrorNotice ( $row ), 0 );
		}
		
		$map = array ();
		$map ['username'] = $data ['username'];
		$map ['status'] = array ('gt', 0 );
		$row = $this->dao->getOneByMap ( $map );
		
		if (! $row) {
			$this->ajaxReturn ( '', '错误：无效用户名。', 0 );
		} else {
			if (! Validate::checkPassword ( $data ['password'], $row ['password'] )) {
				$this->ajaxReturn ( '', '错误：' . $data ['username'] . ' 的密码不正确。', 0 );
			} else {
				//TODO 更新最后登录时间等等
				cookie ( 'auth', tauthcode ( "$row[password]\t$row[userid]", 'ENCODE' ), array ('expire' => $data ['rememberme'] ? TIMESTAMP + 3600 * 24 * 15 : 0 ) );
				$t = ThinkBLOG::getInstance ();
				$t->session->isnew = true;
				tupdatesession ();
				$this->dao->updateUserInfo ( $row ['userid'] );
				$this->_hasLogin = true;
				$this->ajaxReturn ( '', '登录成功', 1 );
			}
		}
	}
	
	/**
	 * 注册界面渲染
	 *
	 * @access public
	 * @return void
	 */
	public function register() {
		if (defined ( '__NO_REGISTER__' )) {
			$this->_login ();
			exit ();
		}
		$this->display ();
	}
	
	/**
	 * 注册业务处理
	 *
	 * @access public
	 * @return void
	 */
	public function registration() {
		
		if (! $this->submitcheck ()) {
			$this->ajaxReturn ( '', '非法提交', 0 );
		}
		
		if (defined ( '__NO_REGISTER__' )) {
			$this->ajaxReturn ( '', '新用户注册暂时关闭。', 0 );
		}
		
		if (false === $this->dao->create ()) {
			$this->ajaxReturn ( '', $this->dao->getError (), 0 );
		}
		
		$password = trandstring ( 8 );
		$username = $this->dao->username;
		$email = $this->dao->email;
		$this->dao->password = Validate::compilePassword ( $password );
		$this->dao->nicename = $username;
		$result = $this->dao->add ();
		
		if ($result !== false) {
			$this->assign ( 'username', $username );
			$this->assign ( 'password', $password );
			$this->assign ( 'url', tget_domain () . U ( '/user/login' ) );
			$content = $this->fetch ( 'Mail:register' );
			$subject = '[' . C ( 'title' ) . '] 注册成功';
			import ( '@.ORG.Email' );
			if (Email::send ( $email, $subject, $content, 1 )) {
				$this->ajaxReturn ( '', '注册完成。请查收我们给您发的邮件。', 1 );
			} else {
				$this->ajaxReturn ( '', '错误：邮件发送失败，请联系管理员。', 0 );
			}
		} else {
			$this->ajaxReturn ( '', '错误：未知错误。', 0 );
		}
	}
	
	/**
	 * 重置密码界面渲染
	 *
	 * @access public
	 * @return void
	 */
	public function lostPassword() {
		$this->display ();
	}
	
	/**
	 * 发送重置密码链接
	 *
	 * @access public
	 * @return void
	 */
	public function sendPassword() {
		
		if (! $this->submitcheck ()) {
			$this->ajaxReturn ( '', '非法提交', 0 );
		}
		
		$this->v->addRule ( 'user', 'required', '错误：请输入用户名或电子邮件地址。' );
		
		if ($row = $this->v->run ( $this->r->from ( 'user' ) )) {
			$this->ajaxReturn ( '', $this->getErrorNotice ( $row ), 0 );
		}
		
		$user = $this->r->filter ( 'strip_tags', 'trim', 'xss' )->user;
		
		/** 验证用户名或邮件地址是否存在 */
		$map = array ();
		$where ['email'] = $user;
		$where ['username'] = $user;
		$where ['_logic'] = 'or';
		$map ['_complex'] = $where;
		$map ['status'] = array ('gt', 0 );
		$row = $this->dao->getOneByMap ( $map );
		
		if ($row) {
			/** 生成key,链接1小时有效  */
			$key = str_replace ( array ('+', '/' ), array ('{}', '()' ), tauthcode ( "$row[userid]\t$row[created]", 'ENCODE', '', 3600 ) );
			$url = tget_domain () . U ( '/user/resetpassword/' . $row ['userid'] . '/' . $key, '', false );
			$this->assign ( 'username', $row ['username'] );
			$this->assign ( 'url', $url );
			$content = $this->fetch ( 'Mail:reset' );
			$subject = '[' . C ( 'title' ) . '] 密码重设';
			import ( '@.ORG.Email' );
			if (Email::send ( $row ['email'], $subject, $content, 1 )) {
				$this->ajaxReturn ( '', '请检查您的邮件，内有确认激活链接。', 1 );
			} else {
				$this->ajaxReturn ( '', '错误：邮件发送失败，请联系管理员。', 0 );
			}
		} else {
			$this->ajaxReturn ( '', '错误：用户名或电子邮件地址无效。', 0 );
		}
	}
	
	/**
	 * 重置密码有效性验证
	 *
	 * @access public
	 * @return void
	 */
	public function resetPassword() {
		$this->v->addRule ( 'userid', 'required', '非法参数' );
		$this->v->addRule ( 'key', 'required', '非法参数' );
		
		if ($row = $this->v->run ( $this->r->from ( 'userid', 'key' ) )) {
			$this->ajaxReturn ( '', $this->getErrorNotice ( $row ), 0 );
		}
		
		$userid = $this->r->filter ( 'int' )->userid;
		$key = $this->r->filter ( 'trim' )->key;
		
		if (! empty ( $key ) && ! empty ( $userid )) {
			
			$key = trim ( $key );
			$userid = intval ( $userid );
			$map = array ();
			$map ['userid'] = $userid;
			$map ['status'] = array ('gt', 0 );
			$row = $this->dao->getOneByMap ( $map );
			@list ( $userid, $created ) = explode ( "\t", tauthcode ( (str_replace ( array ('{}', '()' ), array ('+', '/' ), $key )), 'DECODE' ) );
			if (empty ( $row ) || ($row && $userid != $row ['userid'] && $created != $row ['created'])) {
				$this->error ( '错误：抱歉，该 key 似乎无效。' );
			}
			$this->assign ( 'userid', $userid );
			$this->assign ( 'key', $key );
			$this->display ();
		
		} else {
			redirect ( U ( '/user/login' ) );
		}
	}
	
	/**
	 * 重置密码,
	 *
	 * @access public
	 * @return void
	 */
	public function modify() {
		
		$this->v->addRule ( 'pass1', 'required', '错误：必须填写新密码' );
		$this->v->addRule ( 'pass2', 'required', '错误：必须填写确认新密码' );
		$this->v->addRule ( 'pass1', 'minLength', '错误：为了保证账户安全, 请输入至少六位的密码', 6 );
		$this->v->addRule ( 'pass1', 'maxLength', '错误：为了便于记忆, 密码长度请不要超过十八位', 18 );
		$this->v->addRule ( 'pass2', 'confirm', '错误：您两次输入的密码不符', 'pass1' );
		
		/** 截获验证异常 */
		if ($row = $this->v->run ( $this->r->from ( 'old_password', 'pass1', 'pass2', 'key', 'userid' ) )) {
			$this->ajaxReturn ( '', $this->getErrorNotice ( $row ), 0 );
		}
		
		$_userid = empty ( $this->r->userid ) ? $this->_users ['userid'] : $this->r->filter ( 'int' )->userid;
		$key = empty ( $this->r->key ) ? '' : $this->r->filter ( 'trim' )->key;
		$pass2 = $this->r->filter ( 'trim' )->pass2;
		$old_password = empty ( $this->r->old_password ) ? NULL : $this->r->filter ( 'trim' )->old_password;
		
		$map = array ();
		$map ['userid'] = $_userid;
		$map ['status'] = array ('gt', 0 );
		$row = $this->dao->getOneByMap ( $map );
		@list ( $userid, $created ) = explode ( "\t", tauthcode ( (str_replace ( array ('{}', '()' ), array ('+', '/' ), $key )), 'DECODE' ) );
		if (($row && (! empty ( $key ) && $userid == $row ['userid'] && $created == $row ['created'])) || $this->_users ['userid'] > 0 && $this->_users ['userid'] == $userid && $this->dao->checkUser ( $this->_users ['username'] )) {
			if ($this->dao->editUser ( array ('username' => (empty ( $key ) ? $this->_users ['username'] : $row ['username']), 'old_password' => $old_password, 'password' => $pass2 ), empty ( $key ) ? 0 : 1 )) {
				$this->ajaxReturn ( '', '您的密码已被重置。', 1 );
			} else {
				$this->ajaxReturn ( '', '错误：抱歉，您输入的原密码不正确。', 0 );
			}
		} else {
			$this->ajaxReturn ( '', '错误：抱歉，操作失败。', 0 );
		}
	}

}